#-*- coding: UTF-8 -*- 
# yonggang.huang
# pfs_press.py "管理员:  FE"
from ctypes import *
import os
import os.path
import sys
import time
import subprocess
from time import sleep

find = windll.user32.FindWindowA
postmsg = windll.user32.PostMessageA

WM_CHAR = 0x0102
VK_RETURN = 0x0D

#window window_handle
window_handle = 0
#keystroke interval (second)
keystroke_delay = 0.0
command_delay = 0.0

def set_keystroke_delay(i):
    global keystroke_delay
    keystroke_delay = i

def set_command_delay(i):
    global command_delay
    command_delay = i
    
def send_cmd(s):
    global window_handle, keystroke_delay, command_delay
    for c in s:
        if c == "\r":
            continue
        if c == "\n":
            c = VK_RETURN
        else:
            c = ord(c)
        postmsg(window_handle, WM_CHAR, c, 0)
        sleep(keystroke_delay)
    sleep(command_delay)
 
def press_test():
    print "CND start cmd"
    if len(sys.argv) == 2:
        send_cmd(sys.argv[1] + "\n")
    elif len(sys.argv) == 3:
        send_cmd(sys.argv[1] + " " + sys.argv[2] + "\n")
    elif len(sys.argv) == 4:
        send_cmd(sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + "\n")
    else:
        send_cmd(sys.argv[1] + " " + sys.argv[2] + " " +sys.argv[3] + " " + sys.argv[4] + "\n")
    print "CND cmd end"
    
  
def run(wndname):
    cls = "ConsoleWindowClass"
    global window_handle
    
    import logging
    log_format = '%(filename)s [%(asctime)s] [%(levelname)s] %(message)s'
    logging.basicConfig(filename="logging_test.log",format=log_format,datefmt='%Y-%m-%d %H:%M:%S',filemode='a',level=logging.DEBUG)

    logging.debug("this message should be logged:debug")
    logging.info("this message should be logged:info")
    logging.error("this message should be logged:error")
    while True:
        window_handle = find(cls, wndname)
        if window_handle == 0:
            print "try to find target window", wndname
            sleep(2)
        else:
            print "find target window", wndname
            sleep(0.1)
            break
    press_test()

def main():    
#    if len(sys.argv) < 2:
#        print "less argv distance"
        #return 1
    wndname="Administrator:  US"
    #wndname="US"
	#wndname="D:\TFS\CO\UIH\bin_debug\UsControlNodeDrvDemo.exe"
    #wndname.decode("utf-8")
    #wndname = sys.argv[1]
    run(wndname)
    return 0
if __name__ == "__main__":
    sys.exit(main())
